//
// Created by A on 2024/6/23.
//
#include "config.h"

/**
 *@brief 初始化精灵资源 适用于没有动图的资源
 *@param spirit 精灵指针
 *@param filepath 资源位置
 *@param CroppRect 裁剪位置
 *@param DP_Rect 显示位置 如果显示位置的wh为零则使用裁剪位置的wh
 *@return 0成功 -1失败
 * */


int map_common_init(Mspirit * spirit,char * filepath,Spirit_Rect CroppRect,Spirit_Rect DP_Rect){
    //基础属性 Attribute
    spirit->attribute.key = map;

    //精灵状态 Allstatus
    spirit->Status=idle;

    //当前位置大小 Spirit_Rect
    if(DP_Rect.w==0&&DP_Rect.h==0){
        spirit->Rect.w=CroppRect.w;
        spirit->Rect.h=CroppRect.h;
    }else{
        spirit->Rect.w=DP_Rect.w;
        spirit->Rect.h=DP_Rect.h;
    }

    spirit->Rect.x=DP_Rect.x;
    spirit->Rect.y=DP_Rect.y;

    //武器装备 Weapon


    //动画 AllAnimation

    //动画资源加载
    SDL_Surface *   bmp = IMG_Load(filepath);
    if (bmp == nullptr){
        return -1;
    }
    SDL_Texture * resoures = SDL_CreateTextureFromSurface(ren, bmp);
    SDL_FreeSurface(bmp);

    spirit->mation.idle.type=0;
    spirit->mation.idle.frame_num[spirit->mation.idle.type] = 1;
    spirit->mation.idle.framedata[spirit->mation.idle.type] =(Animation_frame *)malloc(sizeof(Animation_frame)*spirit->mation.idle.frame_num[spirit->mation.idle.type]);//初始5帧

    for (int i = 0; i < spirit->mation.idle.frame_num[spirit->mation.idle.type]; i++) {
        spirit->mation.idle.framedata[spirit->mation.idle.type][i].original_Rect.x=CroppRect.x;
        spirit->mation.idle.framedata[spirit->mation.idle.type][i].original_Rect.y=CroppRect.y;
        spirit->mation.idle.framedata[spirit->mation.idle.type][i].original_Rect.w=CroppRect.w;
        spirit->mation.idle.framedata[spirit->mation.idle.type][i].original_Rect.h=CroppRect.h;
        spirit->mation.idle.framedata[spirit->mation.idle.type][i].delat_time=0;
        spirit->mation.idle.framedata[spirit->mation.idle.type][i].resoures=resoures;
    }
    //动画状态帧加载---运动状态

    //动画状态帧加载---交互状态

    //动画状态帧加载---出现状态

    //动画状态帧加载---死亡状态

    //动画状态帧加载---攻击状态
    return 0;
}




/**
 *@brief
 * 初始化地图相关资源
 * */
int map_init(){

//    Mspirit * ptr =new Mspirit;


    map_fun[1].key = map_grass_key;
    map_fun[1].Mspirit_init = map_common_init;
    map_fun[1].CroppRect.x=0;
    map_fun[1].CroppRect.y=0;
    map_fun[1].CroppRect.h=72;
    map_fun[1].CroppRect.w=72;
    strcpy(map_fun[1].filepatch,Mapfile.c_str());

    map_fun[2].key = map_road_key;
    map_fun[2].Mspirit_init = map_common_init;
    map_fun[2].CroppRect.x=0;
    map_fun[2].CroppRect.y=192;
    map_fun[2].CroppRect.h=24;
    map_fun[2].CroppRect.w=24;
    strcpy(map_fun[2].filepatch,Mapfile.c_str());

    map_fun[3].key = map_water_key;
    map_fun[3].Mspirit_init = map_common_init;
    map_fun[3].CroppRect.x=72;
    map_fun[3].CroppRect.y=120;
    map_fun[3].CroppRect.h=24;
    map_fun[3].CroppRect.w=24;
    strcpy(map_fun[3].filepatch,Mapfile.c_str());

    map_fun[4].key = map_Lotusleaf_key;
    map_fun[4].Mspirit_init = map_common_init;
    map_fun[4].CroppRect.x=96;
    map_fun[4].CroppRect.y=120;
    map_fun[4].CroppRect.h=24;
    map_fun[4].CroppRect.w=24;
    strcpy(map_fun[4].filepatch,Mapfile.c_str());

    map_fun[5].key = map_grassroad_key;
    map_fun[5].Mspirit_init = map_common_init;
    map_fun[5].CroppRect.x=24;
    map_fun[5].CroppRect.y=192;
    map_fun[5].CroppRect.h=24;
    map_fun[5].CroppRect.w=24;
    strcpy(map_fun[5].filepatch,Mapfile.c_str());
    return 0;
}


/**
 * @brief 加载地图数据
 * */
void* map_load(char *filepath){
    if(filepath==NULL) return nullptr;
    FILE * file =fopen(filepath,"r");
    if (file == NULL) {
        perror("fopen");
        return nullptr;
    }
    // 获取文件大小（需要借助fseek和ftell）
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    rewind(file); // 重置文件指针到文件开始

    // 分配内存来读取文件
    char *buffer = (char *)malloc(file_size + 1); // +1 for null terminator
    if (buffer == NULL) {
        perror("malloc");
        fclose(file);
        return nullptr;
    }
    // 读取文件
    size_t bytes_read = fread(buffer, 1, file_size, file);
    if (bytes_read <= 0) {
        fprintf(stderr, "Failed to read entire file.\n");
        free(buffer);
        fclose(file);
        return nullptr;
    }
    buffer[bytes_read] = '\0'; // 添加null终止符（对于文本文件）

    // 输出文件内容（可选）
    printf("File content:\n%s\n", buffer);

    //关闭文件
    fclose(file);
    LNode* maplink=List_init();
    if(maplink==nullptr) return nullptr;
    maplink->Ldata.pp = new Map_head;
    Map_head * headdata =(Map_head *) maplink->Ldata.pp;



    cJSON* cjson_map=nullptr;
    cjson_map=cJSON_Parse(buffer);

    cJSON* cjson_max_h = cJSON_GetObjectItem(cjson_map, "max_h");
    cJSON* cjson_max_w = cJSON_GetObjectItem(cjson_map, "max_w");
    cJSON* cjson_def_x = cJSON_GetObjectItem(cjson_map, "def_x");
    cJSON* cjson_def_y = cJSON_GetObjectItem(cjson_map, "def_y");

    headdata->w =cjson_max_w->valueint;
    headdata->h =cjson_max_h->valueint;
    headdata->def_x=cjson_def_x->valueint;
    headdata->def_y=cjson_def_y->valueint;

    My_Crasg.x = headdata->def_x; //设置地图初始化加载位置
    My_Crasg.y = headdata->def_y;



    cJSON*  cjson_data = cJSON_GetObjectItem(cjson_map, "data");
    unsigned int num =cJSON_GetArraySize(cjson_data);
    for (int i = 0; i <num ; i++) {
        cJSON* cjson_data_item = cJSON_GetArrayItem(cjson_data, i);

        cJSON* cjson_data_item_key =cJSON_GetObjectItem(cjson_data_item, "key");
        cJSON* cjson_data_item_x =cJSON_GetObjectItem(cjson_data_item, "x");
        cJSON* cjson_data_item_y =cJSON_GetObjectItem(cjson_data_item, "y");

        cJSON* cjson_data_item_Filling =cJSON_GetObjectItem(cjson_data_item, "Filling");
        cJSON* cjson_data_item_Filling_x =cJSON_GetObjectItem(cjson_data_item, "Filling_x");
        cJSON* cjson_data_item_Filling_y =cJSON_GetObjectItem(cjson_data_item, "Filling_y");
        cJSON* cjson_data_item_Filling_h =cJSON_GetObjectItem(cjson_data_item, "Filling_h");
        cJSON* cjson_data_item_Filling_w =cJSON_GetObjectItem(cjson_data_item, "Filling_w");


        for (int j = 0; j < map_initfunsize; j++) {
            if(cjson_data_item_key->valueint == map_fun[j].key){
                if(strcmp(cjson_data_item_Filling->valuestring,"true")==0){//使能填充
                    int x_num=cjson_data_item_Filling_w->valueint/map_fun[j].CroppRect.w +
                            (cjson_data_item_Filling_w->valueint%map_fun[j].CroppRect.w?1:0);
                    int y_num=cjson_data_item_Filling_h->valueint/map_fun[j].CroppRect.h +
                             ( cjson_data_item_Filling_h->valueint%map_fun[j].CroppRect.h?1:0);
                    for (int k = 0; k < y_num; k++) {
                        for (int l = 0; l <x_num ; l++) {
                            Mspirit * ptr =new Mspirit;
                            Spirit_Rect dp_rect ={
                                    .x=cjson_data_item_Filling_x->valueint+l*map_fun[j].CroppRect.w,
                                    .y=cjson_data_item_Filling_y->valueint+k*map_fun[j].CroppRect.h,
                                    .w=0,
                                    .h=0
                            };
                            map_fun[j].Mspirit_init(ptr,map_fun[j].filepatch,map_fun[j].CroppRect,dp_rect); //初始化地图精灵
                            int key =  ListLength(maplink);
                            data nodedata={
                                    .key = key,
                                    .pp = ptr
                            };
                            CreateList_R(maplink,nodedata);//加入链表
                        }
                    }

                }else{
                    Mspirit * ptr =new Mspirit;
                    Spirit_Rect dp_rect ={
                            .x=cjson_data_item_x->valueint,
                            .y=cjson_data_item_y->valueint,
                            .w=0,
                            .h=0
                    };
                    map_fun[j].Mspirit_init(ptr,map_fun[j].filepatch,map_fun[j].CroppRect,dp_rect); //初始化地图精灵
                    int key =  ListLength(maplink);
                    data nodedata={
                            .key = key,
                            .pp = ptr
                    };
                    CreateList_R(maplink,nodedata);//加入链表
                }


                break;
            }

        }
    }
    cJSON_Delete(cjson_map);

    free(buffer);
    map_set_linkhandle(maplink);
    return maplink;
}

/**
 * @brief 一次渲染地图精灵链表
 * @param pnode 要渲染的链表
 * @return 链表中的精灵个数
 * */
int Mmap_Linkrun(LNode* pnode){
    LNode* p;
    int i = 0;
    Map_head * headdata =(Map_head *) pnode->Ldata.pp;
    if(headdata== nullptr) return -1;
    p = pnode->next;
    Mspirit * Pspirit=NULL;
    while (p) {
        Pspirit =( Mspirit *) p->Ldata.pp;
        if(Crash_Contain(Pspirit->Rect)==0)//如果在加载范围内
            Pspirit->Mspirit_run();
        p = p->next;
        i++;
    }
    return i;
}


static  LNode * linkhandle=nullptr;
/**
 * 设置地图链表头节点指针
 *@return 0 设置成功 -1 设置失败
 * */
int map_set_linkhandle(LNode *handle){
    if(handle!= nullptr){
        linkhandle = handle;
        return 0;
    }
    return -1;
}
/**
 *获取当前地图的链表头节点
 *
 * */
LNode *map_get_linkhandle(void){
    if(linkhandle!= nullptr){
        return linkhandle;
    }
    return nullptr;
}